#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
main窗口居中显示
"""

import sys
from PyQt5.QtWidgets import (QWidget, QToolTip,QPushButton, QApplication)
from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QDesktopWidget#窗口信息
from PyQt5.QtWidgets import QMainWindow

from PyQt5.QtCore import QCoreApplication #退出操作

class Example(QMainWindow):

    def __init__(self):
        super().__init__()# 父类的初始化
        self.initUI()

    def test(self):
        print("测试下按键操作")
        QCoreApplication.instance().quit()

    def closeEvent(self, event):
        # event.ignore()
        # return #如果直接return，不执行event.ignore()，还是会退出的
        reply = QMessageBox.question(self, '这是显示在messageBox的标题',
                                     "你要退出吗的提示?", QMessageBox.Yes |
                                     QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def initUI(self):
        QToolTip.setFont(QFont('SansSerif', 10)) #使用10px大小的SansSerif字体，可以不需要
        self.setToolTip('这是主窗口的提示')

        btn = QPushButton('退出按键', self)
        btn.setToolTip('这是一个 <b>退出按键</b> 控件')
        btn.resize(btn.sizeHint()) #setHint()方法给了按钮一个推荐的大小
        btn.move(50, 50)

        btn.clicked.connect(self.test)  # 绑定到退出
        #btn.clicked.connect(QCoreApplication.instancae().quit) #绑定到退出

        self.setGeometry(300, 300, 300, 220)# 坐标，大小
        self.setWindowTitle('测试help提示')
        self.setWindowIcon(QIcon('icon.png'))
        self.center()

        self.statusBar().showMessage('这是状态栏文字')# 注意，这里的父类是QMainWindow，
                                                        # 之前是class Example(QWidget):


        self.show()

    def center(self):
        qr = self.frameGeometry()
        #print(qr) #这里会打印PyQt5.QtCore.QRect(300, 300, 300, 220)
        #print(QDesktopWidget().availableGeometry())#PyQt5.QtCore.QRect(0, 0, 1366, 728)
        cp = QDesktopWidget().availableGeometry().center()
        #print(cp)# 这里会打印PyQt5.QtCore.QPoint(682, 363)
        qr.moveCenter(cp)
        #print(qr.topLeft()) #PyQt5.QtCore.QPoint(533, 254)
        self.move(qr.topLeft())

    def center0(self):  # 主窗口居中显示函数
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        print(size)
        self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Example()
    sys.exit(app.exec_())